package com.creatshare.service.impl;

import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.creatshare.bean.Bug;
import com.creatshare.bean.Page;
import com.creatshare.dao.BugDao;
import com.creatshare.service.BugService;
import com.creatshare.util.ConfigUtils;

@Service
public class BugServiceImpl implements BugService {
	@Resource
	private BugDao bugDao;

	@Override
	public int update(Bug bug) {
		try {
			return bugDao.updateByPrimaryKey(bug);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	@Override
	public int insert(Bug bug) {
		try {
			return bugDao.insert(bug);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	@Override
	public Bug getBugById(int bugid) {
		return bugDao.selectByPrimaryKey(bugid);
	}

	@Override
	public Page getBugByPro(int currentPage, int projectid) {
		int totalRecord = bugDao.getBugRecordByPro(projectid);
		int pageSize = Integer.parseInt(ConfigUtils.getValue("pageSize"));
		Page page = new Page(currentPage, pageSize, totalRecord);
		List<Bug> bugList = null;
		try {
			bugList = bugDao.getBugByPro(projectid, page.getStartIndex(), pageSize);
			if (bugList == null || bugList.isEmpty()) {
				page.setRecordList(Collections.emptyList());
			} else {
				page.setRecordList(bugList);
			}
		} catch (Exception e) {
			page.setRecordList(Collections.emptyList());
			e.printStackTrace();
		}
		return page;
	}

	@Override
	public Page getBugByState(int currentPage, int bugstate) {
		int pageSize = Integer.parseInt(ConfigUtils.getValue("pageSize"));
		int totalRecord = bugDao.getBugRecordByState(bugstate);
		Page page = new Page(currentPage, pageSize, totalRecord);
		List<Bug> bugList = null;
		try {
			bugList = bugDao.getBugByState(bugstate, page.getStartIndex(), pageSize);
			if (bugList == null || bugList.isEmpty()) {
				page.setRecordList(Collections.emptyList());
			} else {
				page.setRecordList(bugList);
			}
		} catch (Exception e) {
			page.setRecordList(Collections.emptyList());
			e.printStackTrace();
		}
		return page;
	}

	@Override
	public Page getBugByLater(int currentPage) {
		int pageSize = Integer.parseInt(ConfigUtils.getValue("pageSize"));
		int totalRecord = bugDao.getBugRecord();
		Page page = new Page(currentPage, pageSize, totalRecord);
		List<Bug> bugList = null;
		try {
			bugList = bugDao.getBugByLater(page.getStartIndex(), pageSize);
			if (bugList == null || bugList.isEmpty()) {
				page.setRecordList(Collections.emptyList());
			} else {
				page.setRecordList(bugList);
			}
		} catch (Exception e) {
			page.setRecordList(Collections.emptyList());
			e.printStackTrace();
		}
		return page;
	}
}
